# Copyright (c) Mengning Software. 2023. All rights reserved.
#
# Super IDE licensed under GNU Affero General Public License v3 (AGPL-3.0) .
# You can use this software according to the terms and conditions of the AGPL-3.0.
# You may obtain a copy of AGPL-3.0 at:
#
#    https://www.gnu.org/licenses/agpl-3.0.txt
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the AGPL-3.0 for more details.

from os import chdir, getcwd, readlink, remove, symlink, walk
from os.path import exists, islink, join, relpath
from sys import exit as sys_exit


def fix_symlink(root, fname, brokenlink):
    print(root, fname, brokenlink)
    prevcwd = getcwd()

    chdir(root)
    remove(fname)
    symlink(relpath(brokenlink, root), fname)
    chdir(prevcwd)


def main():
    for root, dirnames, filenames in walk("."):
        for f in filenames:
            path = join(root, f)
            if not islink(path) or exists(path):
                continue
            fix_symlink(root, f, readlink(path))


if __name__ == "__main__":
    sys_exit(main())
